package sjtu.ist.ecommerce.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
  
public final class XMLParser {  
	private static final String PACKAGE_NAME="sjtu.ist.ecommerce.model";
  
    public XMLParser() {}  
    
    public Object unmarshal(InputStream xml, Class<?> clazz){  
        Object obj = null;            
        try {  
            JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName(),getClass().getClassLoader());  
            Unmarshaller u = jc.createUnmarshaller();  
            BufferedReader brd = new BufferedReader(new InputStreamReader(xml,"utf-8"));
    	    StreamSource source = new StreamSource(brd);
            obj = u.unmarshal(source,clazz).getValue(); 
            brd.close();
        } catch (JAXBException e) {
        	System.out.println(e.getMessage());
        	e.printStackTrace();
            //throw new RuntimeException("Can't unmarshal the XML file, error message: " + e.getMessage());  
        } catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return obj;  
    }  
      
    public String marshal(Object obj, Class<?> clazz) {  
        String result = null;  
          
        try {  
            JAXBContext jc = JAXBContext.newInstance(clazz.getPackage().getName());  
            Marshaller m = jc.createMarshaller();                
            StringWriter writer = new StringWriter();                
            m.marshal(obj, writer);                
            result = writer.toString();  
        } catch (JAXBException e) {  
            throw new RuntimeException("Can't marshal the XML file, error message: " + e.getMessage());  
        }  
                    
        return result;  
    }  
}  
